package com.lanou.utp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou.utp.entity.Paging;
import com.lanou.utp.entity.ResponseData;
import com.lanou.utp.entity.Teachlink;
import com.lanou.utp.mapper.TeachingMapper;
import com.lanou.utp.service.TeachingServcie;
import com.lanou.utp.utils.IdAndName;
import com.lanou.utp.utils.TeachLinkQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author MaQingYun
 */
@Transactional
@Service
public class TeachingServcieImpl implements TeachingServcie {

    @Resource
    private TeachingMapper teachingMapper;


    @Override
    public ResponseData getTeachlinks(TeachLinkQuery query) {
        Page<Object> page1 = PageHelper.offsetPage((query.getPage() - 1) * Paging.size, Paging.size);
        List<Teachlink> teachlinkList = this.teachingMapper.getTeachlinks(query);
        for (Teachlink teachlink : teachlinkList) {
            if (teachlink.getStatus()==0){
                teachlink.setEditable(true);
            } else {
                teachlink.setEditable(false);
            }
        }
        Paging paging = new Paging(query.getPage(),page1.getTotal());
        return new ResponseData(teachlinkList,paging);
    }

    @Transactional
    @Override
    public void addTeachingLink(Teachlink teachlink) {
        this.teachingMapper.addTeachingLink(teachlink);
        this.teachingMapper.insertTeachLinkTecher(teachlink.getId(), teachlink.getTeacherIds());
    }

    @Override
    public List<IdAndName> getTeachlinkTeachers(long id) {
        return this.teachingMapper.getTeachlinkTeachers(id);
    }

    @Override
    public void updateTeachlinkStatus(Long id) {
        this.teachingMapper.updateTeachlinkStatus(id);
    }

    @Transactional
    @Override
    public Teachlink getTeachlinkById(Long id) {
        Teachlink teachlinkById = this.teachingMapper.getTeachlinkById(id);
        List<Long>  teacherIds = this.teachingMapper.getThahlinkTeachers(id);
        teachlinkById.setTeacherIds(teacherIds);
        return teachlinkById;
    }

    @Transactional
    @Override
    public void updateTeachlink(Teachlink teachlink) {
        this.teachingMapper.updateTeachlink(teachlink);
        this.teachingMapper.deleteTeachlinkTeacher(teachlink.getId());
        this.teachingMapper.insertTeachLinkTecher(teachlink.getId(),teachlink.getTeacherIds());
    }

    @Override
    public void deleteTeachinkById(Long id) {
        this.teachingMapper.deleteTeachinkById(id);
    }


}
